const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/* 日期转字符串 */
const dateToStr = (formatStr = 'yyyy-MM-dd HH:mm:ss', date = new Date()) => {
  let str = formatStr;
  let Week = ['日', '一', '二', '三', '四', '五', '六'];
  str = str.replace(/yyyy|YYYY/, date.getFullYear());
  str = str.replace(/yy|YY/, (date.getYear() % 100) > 9 ? (date.getYear() % 100).toString() : '0' + (date.getYear() % 100));
  str = str.replace(/MM/, date.getMonth() >= 9 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1));
  str = str.replace(/M/g, date.getMonth());
  str = str.replace(/w|W/g, Week[date.getDay()]);

  str = str.replace(/dd|DD/, date.getDate() > 9 ? date.getDate().toString() : '0' + date.getDate());
  str = str.replace(/d|D/g, date.getDate());

  str = str.replace(/hh|HH/, date.getHours() > 9 ? date.getHours().toString() : '0' + date.getHours());
  str = str.replace(/h|H/g, date.getHours());
  str = str.replace(/mm/, date.getMinutes() > 9 ? date.getMinutes().toString() : '0' + date.getMinutes());
  str = str.replace(/m/g, date.getMinutes());

  str = str.replace(/ss|SS/, date.getSeconds() > 9 ? date.getSeconds().toString() : '0' + date.getSeconds());
  str = str.replace(/s|S/g, date.getSeconds());

  return str;
}

/**
 * 字符串转时间（yyyy-MM-dd HH:mm:ss）
 * result （分钟）
 */
const stringToDate = fDate => {
  let fullDate = fDate.split("-");
  return new Date(fullDate[0], fullDate[1] - 1, fullDate[2], 0, 0, 0);
}

/* 处理时间戳字符串 */
const handleTime = data => {
  if (data.freshtime !== '0' && data.freshtime !== undefined) {
    data.freshtime = dateToStr("yyyy-MM-dd HH:mm:ss", new Date(parseInt(data.freshtime + '000')))
  } else {
    data.createtime = dateToStr("yyyy-MM-dd HH:mm:ss", new Date(parseInt(data.createtime + '000')))
  }
  return data
}

/* 取经纬度信息 */
const getLocation = (reset = false, callback) => {
  if (typeof reset == 'function') {
    callback = reset
    reset = false
  }
  if (reset) {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        wx.setStorage({
          key: "location",
          data: res
        })
        callback && callback(res)
      },
      fail: (err) => {
        wx.getSetting({
          success: (res) => {
            if (res.authSetting['scope.userLocation'] == false) {
              wx.showModal({
                title: '是否要打开设置页面重新授权',
                content: '需要获取您的公开信息(昵称，头像，地址等),请到小程序的设置中打开授权',
                confirmText: '去设置',
                success: function (res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success: (res) => {
                        if (res.authSetting['scope.userLocation']) {
                          getLocation(true, callback)
                          return
                        }
                      }
                    })
                  }
                  callback && callback('')
                }
              })
            }
          }
        })
      }
    })
  } else {
    wx.getStorage({
      key: 'location',
      success: function (res) {
        callback && callback(res.data)
      },
      fail() {
        getLocation(true, callback)
      }
    })
  }
}

const getCurrentDate = n => {
  let date = new Date();
  let seperator1 = "-";
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  let currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}

/**
 * 计算两个日期相差几天
 * cusDate 当前时间
 * oriDate  比较时间
 * 返回 正数为cusDate>oriDate
 */
const calculateTime = (cusDate, oriDate) => {
  var cusTime = cusDate.getTime();
  var oriTime = oriDate.getTime();
  return (cusTime - oriTime) / (1000 * 60 * 60 * 24)
}

module.exports = {
  formatTime: formatTime,
  handleTime: handleTime,
  getLocation: getLocation,
  getCurrentDate: getCurrentDate,
  calculateTime: calculateTime,
  dateToStr: dateToStr,
  stringToDate: stringToDate
}
